package com.cskt.itripauth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cskt.common.constants.ErrorCodeEnum;
import com.cskt.common.entity.ItripUser;
import com.cskt.common.exception.ServiceException;
import com.cskt.itripauth.config.EmailConfig;
import com.cskt.itripauth.service.IAuthTripUserService;
import com.cskt.itripauth.util.EmailUtil;
import com.cskt.itripauth.util.RedisUtil;
import com.cskt.mapper.ItripUserMapper;
import com.cskt.util.MD5;
import com.zhenzi.sms.ZhenziSmsClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class AuthTripUserServiceImpl implements IAuthTripUserService {
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ItripUserMapper itripUserMapper;
    @Resource
    private EmailConfig emailConfig;
    @Resource
    private EmailUtil emailUtil;

    @Value(value = "${sms.apiUrl}")
    private String apiUrl;
    @Value(value = "${sms.appId}")
    private String appId;
    @Value(value = "${sms.appSecret}")
    private String appSecret;

    @Override
    public void sendSMS(String phone) {
        //验证验证码是否发送超过三次
        Integer count = 0;//默认等于零
        if (redisUtil.hasKey("count_" + phone)) {
            count = (Integer) redisUtil.get("count_" + phone);
            if (count > 3) {
                throw new ServiceException(ErrorCodeEnum.SMS_VERIFICATION_CODE_COUNT_ERROR);
            }
        }
        //判断当前手机受否发送过验证码，如果发送过，就不重复发送
        if (redisUtil.hasKey("code_" + phone)) {
            throw new ServiceException(ErrorCodeEnum.SMS_VERIFICATION_CODE_COUNT_EXIST);
        }
        //生成验证码
        Random random = new Random();
        Integer codeSMS = random.nextInt(899999) + 100000;
        //发送短信
        ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
        Map<String, Object> params = new HashMap<String, Object>();
        //发送号码 15364274341
        params.put("number", phone);
        //使用的短信模板
        params.put("templateId", "6056");
        //模板使用的参数
        String[] templateParams = new String[2];
        templateParams[0] = codeSMS.toString();
        templateParams[1] = "5";
        params.put("templateParams", templateParams);
        String result = null;
        try {
            result = client.send(params);
        } catch (Exception e) {
            throw new ServiceException(ErrorCodeEnum.SMS_VERIFICATION_CODE_OUT_ERROR);
        }
        System.out.println("短信验证码："+codeSMS);
        System.out.println("发送短信返回结果:" + result);
        //将验证码存储到redis中
        redisUtil.set("code_" + phone, codeSMS);
        redisUtil.expire("code_" + phone, 5 * 60);//设置验证码有效时间
        redisUtil.set("count_" + phone, count + 1);//缓存短信发送次数
        redisUtil.expire("count_" + phone, 24 * 60 * 60);//重置发送短信次数时间
    }

    @Override
    public void registerSMS(ItripUser itripUser, String code) {
        //查看当前手机号是否发送了短信
        if (!redisUtil.hasKey("code_" + itripUser.getUserCode())) {
            //还没有发送验证码就校验
            throw new ServiceException(ErrorCodeEnum.SMS_VERIFICATION_CODE_INPUT_ERROR);
        }
        String redisCode = redisUtil.get("code_" + itripUser.getUserCode()).toString();
        if (redisCode.equals(code)) {
            itripUser.setActivated(1);//默认激活状态
            Date createDate=new Date();
            itripUser.setCreationDate(createDate);//填充创建时间
            itripUser.setModifyDate(createDate);//更新时间
            String password = itripUser.getUserPassword();//拿到表单输入的密码
            password=password+createDate.toString();//将密码和密码盐拼接
            password = MD5.getMd5(password, 32);//进行密码加密
            itripUser.setUserPassword(password);
            itripUserMapper.insert(itripUser);
        } else {
            throw new ServiceException(ErrorCodeEnum.SMS_VERIFICATION_CODE_INPUT_ERROR);
        }
    }

    @Override
    public void registerEmail(ItripUser itripUser) {
        //查看是否是一个注册了，但是没有激活的状态
        QueryWrapper<ItripUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_code", itripUser.getUserCode());
        ItripUser user = itripUserMapper.selectOne(queryWrapper);
        if (user != null && user.getActivated() == 0) {
            //那么就把旧的数据删除
            itripUserMapper.delete(queryWrapper);
        }
        itripUser.setActivated(0);//邮箱注册，需要注册后进行激活
        Date createDate=new Date();
        itripUser.setCreationDate(createDate);//填充创建时间
        itripUser.setModifyDate(createDate);//更新时间
        String password = itripUser.getUserPassword();//拿到表单输入的密码
        password=password+createDate.toString();//将密码和密码盐拼接
        password = MD5.getMd5(password, 32);//进行密码加密
        itripUser.setUserPassword(password);
        itripUserMapper.insert(itripUser);
        //新增之后，往redis中存储激活信息，将邮箱作为key，将生成的一个地址作为value，访问这个value就可以激活账号
        String key = MD5.getMd5(itripUser.getUserCode(), 16);
        redisUtil.set(key, itripUser.getUserCode());
        redisUtil.expire(key, 30 * 60);//30分钟内可以激活
        String title="爱旅行邮箱注册";
        String context="您在爱旅行进行了注册，请30分钟内前往 "+emailConfig.getUrl()+"/"+key+" 进行激活！";
        //发送邮件
        emailUtil.sendStringEmail(itripUser.getUserCode(),title,context);
    }

    @Override
    public void activation(String key) {
        if (!redisUtil.hasKey(key)) {
            throw new ServiceException(ErrorCodeEnum.SMS_VERIFICATION_CODE_NOT_EXIST);
        }
        String userCode = redisUtil.get(key).toString();
        QueryWrapper<ItripUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_code",userCode);
        ItripUser itripUser = itripUserMapper.selectOne(queryWrapper);
        itripUser.setActivated(1);
        itripUserMapper.updateById(itripUser);
    }


}
